Day 24 - React Fetch 向後端API請求資料(1)
上一章實作了Fetch API獲取Member資料
今天我們要拿證照跟廠商資料
Certificate.js
import React, { Component } from 'react';
import {
    Container,
    Table
} from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.css';
import MyNavbar from './MyNavbar';
class Certificate extends Component {
    constructor(props) {
        super(props);
        this.state = { certificates: [] };
    }
    componentDidMount() {
        fetch('/api/certificates').then(response => response.json())
            .then(data => this.setState({ certificates: data }));
    }
    render() {
        const { certificates } = this.state;
        console.log(certificates);
        const certificateList = certificates.map(certificate => {
            return <tr key={certificate.certificateId}>
                <td>{certificate.name}</td>
                <td>{certificate.skill.name}</td>
                <td>{certificate.company.name}</td>
            </tr>
        });
        return (
            <div>
                <MyNavbar />
                <Container fluid>
                    <h3>Certificate</h3>
                    <Table className="mt-3">
                        <thead>
                            <tr>
                                <th>證照名稱</th>
                                <th>技能名稱</th>
                                <th>發照機構</th>
                            </tr>
                        </thead>
                        <tbody>
                            {certificateList}
                        </tbody>
                    </Table>
                </Container>
            </div>
        );
    }
}
export default Certificate;
Vendor.js
import React, { Component } from 'react';
import {
    Container,
    Table
} from 'reactstrap';
import MyNavbar from './MyNavbar';
class Vendor extends Component {
    constructor(props) {
        super(props);
        this.state = { vendors: [] };
    }
    componentDidMount() {
        fetch('/api/vendors').then(response => response.json())
            .then(data => this.setState({ vendors: data }));
    }
    render() {
        const { vendors } = this.state;
        const vendorList = vendors.map(vendor => {
            return <tr key={vendor.vendorId}>
                <td>{vendor.name}</td>
            </tr>
        });
        return (
            <div>
                <MyNavbar />
                <Container fluid>
                    <h3>Vendor</h3>
                    <Table className="mt-4">
                        <thead>
                        <tr>
                            <th>協辦單位</th>
                        </tr>
                        </thead>
                        <tbody>
                            {vendorList}
                        </tbody>
                    </Table>
                </Container>
            </div>
        )
    }
}
export default Vendor;
大家現在應該對Fetch API比較熟悉了, 下一章會教如何控制導頁
Day 26 - React Router And Link